package com.atmilan.quartz.utils.product;

import com.alibaba.fastjson.JSONObject;
import com.atmilan.quartz.config.RestTemplateConfig;
import com.atmilan.quartz.model.dto.folli.FolliProductResDTO;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;

/**
 * 拉取商品源数据
 */

@Slf4j
@Service
public class FolliProductUtil {

    @Autowired
    private RestTemplateConfig restTemplateConfig;
    @Value("${folli.url}")
    private String folliUrl;
    @Value("${folli.key}")
    private String folliKey;
    @Value("${folli.company}")
    private String folliCompany;

    /**
     * 获取folli商品列表
     * @return
     */
    public FolliProductResDTO getFolliProductList(int pageNo, int pageSize) throws JsonProcessingException {
        FolliProductResDTO folliProductResDTO = null;
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.add("API-KEY", folliKey);
            headers.add("API-COMPANY", folliCompany);
            JSONObject param = new JSONObject();
            param.put("page_number",pageNo);
            param.put("page_size",pageSize);
            HttpEntity<JSONObject> requestEntity = new HttpEntity<>(param, headers);
            RestTemplate restTemplate = restTemplateConfig.restTemplate();
            ResponseEntity<String> response = restTemplate.exchange(folliUrl + "zcmk_listproducts", HttpMethod.GET, requestEntity, String.class);
            if (HttpStatus.OK != response.getStatusCode()) {
                JSONObject message = JSONObject.parseObject(response.getBody());
                String errorMessage = message.getString("error");
                log.info("--------------- 获取folli商品列表异常{} ---------------", errorMessage);
            }
            ObjectMapper mapper = new ObjectMapper();
            FolliProductResDTO.FolliGoodsRes[] folliGoodsRes = mapper.readValue(response.getBody(), FolliProductResDTO.FolliGoodsRes[].class);
            folliProductResDTO = new FolliProductResDTO();
            folliProductResDTO.setProducts(Arrays.asList(folliGoodsRes));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return folliProductResDTO;
    }

}
